package ossFile

import (
	"common/comOss"
	"common/dao/model"
	comJwt "common/jwt"
	"common/utils"
	"context"
	"fmt"
	"github.com/jinzhu/copier"
	"mime/multipart"
	"net/http"
	"strings"
	"time"

	"file/internal/svc"
	"file/internal/types"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/zeromicro/go-zero/core/logx"
)

type OssUploadFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	req    *http.Request
}

func NewOssUploadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *OssUploadFileLogic {
	return &OssUploadFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		req:    r,
	}
}

func (l *OssUploadFileLogic) OssUploadFile() (resp *types.SysFileResp, err error) {
	// todo: add your logic here and delete this line
	user, err := comJwt.GetUser(l.ctx)
	if err != nil {
		return nil, err
	}
	resp = &types.SysFileResp{}
	file, m, err := l.req.FormFile("file")
	if err != nil {
		return nil, err
	}
	defer func(file multipart.File) {
		err := file.Close()
		if err != nil {
			return
		}
	}(file)

	uuid := utils.GetUuid()
	Filename := m.Filename
	size := m.Size
	tsar := utils.GetExtension(Filename)
	response, err := comOss.GetOssResponse(l.svcCtx.Config.OSS)
	if err != nil {
		return nil, err
	}
	// 创建 OSS 客户端
	client, err := oss.New(l.svcCtx.Config.OSS.Pint, response.Credentials.AccessKeyId, response.Credentials.AccessKeySecret, oss.SecurityToken(response.Credentials.SecurityToken))
	if err != nil {
		return nil, err
	}
	// 获取存储空间
	bucket, err := client.Bucket(l.svcCtx.Config.OSS.Bucket)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	today := time.Now().Format("20060102") // 格式化为年月日
	objectKey := today + "/" + uuid + "." + tsar
	// 检查文件夹是否存在，不存在则创建
	isExist, err := bucket.IsObjectExist(today + "/")
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	}
	if !isExist {
		err := bucket.PutObject(today+"/", strings.NewReader(""))
		if err != nil {
			fmt.Println("Error:", err)
			return nil, err
		}
	}
	err = bucket.PutObject(objectKey, file)
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	}

	fmt.Println(objectKey)
	// 生成永久有效的访问链接
	signedURL, err := bucket.SignURL(objectKey, oss.HTTPGet, 31536000000)
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}
	t := time.Now()
	sysFile := model.SysFile{
		CreateTime: &t,
		UUID:       uuid,
		Size:       size,
		Name:       Filename,
		Suffix:     "." + tsar,
		Path:       signedURL,
		UserID:     user.UUID,
	}
	err = l.svcCtx.DB.Create(&sysFile).Error
	if err != nil {
		return nil, err
	}
	err = copier.Copy(resp, sysFile)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
